<template>
    <el-card>
        <div class="header-bar">
            <span class="title">设备分组管理</span>
            <el-input v-model="filterText" placeholder="搜索分组" size="small" style="width:200px;margin-right:10px;"
                clearable />
            <el-button type="primary" size="small" @click="onAddRoot">新增顶级分组</el-button>
        </div>
        <el-table :data="filteredTreeData" row-key="id" border style="width: 100%; margin-top:16px;"
            :default-expand-all="true" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column prop="name" label="分组名称" min-width="180" />
            <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
            <el-table-column prop="order" label="排序" width="80" />
            <el-table-column prop="desc" label="描述" min-width="200" />
            <el-table-column label="操作" width="250">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="onEdit(scope.row)">编辑</el-button>
                    <el-button size="small" @click="onAddChild(scope.row)">新增子分组</el-button>
                    <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 编辑/新增弹窗 -->
        <el-dialog v-model="editVisible" :title="editForm.id ? '编辑分组' : '新增分组'">
            <el-form :model="editForm" label-width="80px">
                <el-form-item label="分组名称">
                    <el-input v-model="editForm.name" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="editForm.status">
                        <el-option label="启用" value="enabled" />
                        <el-option label="停用" value="disabled" />
                    </el-select>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number v-model="editForm.order" :min="1" :max="9999" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="editForm.desc" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const initialTree = [
    {
        id: 1,
        name: '总院区',
        status: 'enabled',
        order: 1,
        desc: '总院区所有设备',
        children: [
            { id: 2, name: '急诊科', status: 'enabled', order: 1, desc: '急诊科相关设备', children: [] },
            { id: 3, name: '手术室', status: 'enabled', order: 2, desc: '手术室设备分组', children: [] },
            { id: 4, name: 'ICU重症监护室', status: 'enabled', order: 3, desc: 'ICU相关监护设备', children: [] },
            { id: 5, name: '放射科', status: 'enabled', order: 4, desc: '放射影像设备', children: [] },
            { id: 6, name: '检验科', status: 'enabled', order: 5, desc: '实验室和检验设备', children: [] }
        ]
    },
    {
        id: 7,
        name: '分院区',
        status: 'enabled',
        order: 2,
        desc: '分院区所有设备',
        children: [
            { id: 8, name: '内科', status: 'enabled', order: 1, desc: '分院区内科设备', children: [] },
            { id: 9, name: '外科', status: 'enabled', order: 2, desc: '分院区外科设备', children: [] },
            { id: 10, name: '体检中心', status: 'enabled', order: 3, desc: '健康体检中心相关设备', children: [] }
        ]
    }
]

const treeData = ref(JSON.parse(JSON.stringify(initialTree)))
const filterText = ref('')

const filteredTreeData = computed(() => {
    if (!filterText.value) return treeData.value
    // 递归过滤
    function filter(arr) {
        return arr
            .map(item => ({
                ...item,
                children: item.children ? filter(item.children) : []
            }))
            .filter(
                item =>
                    item.name.includes(filterText.value) ||
                    (item.children && item.children.length)
            )
    }
    return filter(treeData.value)
})

// 弹窗表单
const editVisible = ref(false)
const editForm = reactive({ id: null, parentId: null, name: '', status: 'enabled', order: 1, desc: '' })

function onAddRoot() {
    Object.assign(editForm, { id: null, parentId: null, name: '', status: 'enabled', order: 1, desc: '' })
    editVisible.value = true
}
function onAddChild(parent) {
    Object.assign(editForm, { id: null, parentId: parent.id, name: '', status: 'enabled', order: 1, desc: '' })
    editVisible.value = true
}
function onEdit(row) {
    Object.assign(editForm, { ...row, parentId: findParentId(treeData.value, row.id) })
    editVisible.value = true
}
function onSave() {
    if (!editForm.name.trim()) {
        ElMessage.warning('请输入分组名称')
        return
    }
    if (editForm.id) {
        updateNode(treeData.value, editForm.id, { ...editForm })
        ElMessage.success('修改成功')
    } else {
        const newId = Date.now()
        const newNode = { ...editForm, id: newId, children: [] }
        if (editForm.parentId) {
            addChild(treeData.value, editForm.parentId, newNode)
        } else {
            treeData.value.push(newNode)
        }
        ElMessage.success('新增成功')
    }
    editVisible.value = false
}
function onDelete(row) {
    removeNode(treeData.value, row.id)
}
function statusFormatter(row) {
    return row.status === 'enabled' ? '启用' : '停用'
}
// -------- 工具函数 -------
function findParentId(tree, id, parentId = null) {
    for (const item of tree) {
        if (item.id === id) return parentId
        if (item.children?.length) {
            const found = findParentId(item.children, id, item.id)
            if (found) return found
        }
    }
    return null
}
function updateNode(tree, id, data) {
    for (const item of tree) {
        if (item.id === id) Object.assign(item, data)
        else if (item.children?.length) updateNode(item.children, id, data)
    }
}
function removeNode(tree, id) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (tree[i].id === id) tree.splice(i, 1)
        else if (tree[i].children?.length) removeNode(tree[i].children, id)
    }
}
function addChild(tree, parentId, child) {
    for (const item of tree) {
        if (item.id === parentId) {
            item.children = item.children || []
            item.children.push(child)
            return true
        }
        if (item.children?.length) {
            if (addChild(item.children, parentId, child)) return true
        }
    }
    return false
}
</script>

<style scoped>
.header-bar {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.title {
    font-size: 20px;
    font-weight: bold;
    margin-right: 20px;
}
</style>
